package com.apo1o.cmscore.interceptor;

import com.apo1o.cmscore.exception.ServiceException;
import com.apo1o.cmscore.util.JWTUtil;
import com.apo1o.cmscore.util.ResultCode;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: Apo1o.
 * @Date: 2023/11/16-11-16-15:02
 * @Description： com.apo1o.cmscore.interceptor
 */
@Slf4j

public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }

        // 从 HTTP请求头中取出 token
        String token = httpServletRequest.getHeader("Authorization");
        if (token == null) {
            throw new RuntimeException("无token，请重新登录");
        }

        // 验证 token
        try {
            //解析JWT
            Claims claims = JWTUtil.parseJWT(token);
            String id = String.valueOf(claims.get("userId"));
            //专门为 /auth/user/info 提供服务
            httpServletRequest.setAttribute("userId",id);
        }catch (ExpiredJwtException e){
            //登录到期
            throw new RuntimeException("登录到期");
        }catch (MalformedJwtException e){
            //令牌失效
            throw new RuntimeException("令牌失效");
        }catch (Exception e){
            log.error(e.getMessage());
            //服务器内部错误
            throw new ServiceException(ResultCode.SYSTEM_INNER_ERROR);
        }

        return true;
    }
}
